package com.iscas.green.extralindextest.servlet;

import com.iscas.green.extralindextest.service.FileIOService;
import com.iscas.green.extralindextest.service.TimerService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * 提供计时器和文件IO功能的UI界面
 */
@WebServlet(name = "utilityServlet", urlPatterns = "/utility")
public class UtilityServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;
    private static final Logger log = LoggerFactory.getLogger(UtilityServlet.class);
    
    private TimerService timerService;
    private FileIOService fileIOService;
    
    @Override
    public void init() throws ServletException {
        super.init();
        WebApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
        timerService = ctx.getBean(TimerService.class);
        fileIOService = ctx.getBean(FileIOService.class);
        log.info("UtilityServlet初始化成功");
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        
        String action = request.getParameter("action");
        
        if (action == null) {
            // 显示主页面
            showMainPage(request, response);
            return;
        }
        
        switch (action) {
            case "startTimer":
                handleStartTimer(request, response);
                break;
            case "stopTimer":
                handleStopTimer(request, response);
                break;
            case "listFiles":
                handleListFiles(request, response);
                break;
            case "readFile":
                handleReadFile(request, response);
                break;
            default:
                showMainPage(request, response);
                break;
        }
    }
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        
        String action = request.getParameter("action");
        
        if ("writeFile".equals(action)) {
            handleWriteFile(request, response);
        } else {
            // 重定向到GET请求
            response.sendRedirect(request.getContextPath() + "/utility");
        }
    }
    
    private void showMainPage(HttpServletRequest request, HttpServletResponse response) 
            throws IOException {
        
        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().println("<!DOCTYPE html>");
        response.getWriter().println("<html><head>");
        response.getWriter().println("<meta charset='UTF-8'>");
        response.getWriter().println("<title>实用工具</title>");
        response.getWriter().println("<style>");
        response.getWriter().println("body { font-family: Arial, sans-serif; margin: 0; padding: 20px; background-color: #f5f5f5; }");
        response.getWriter().println(".container { max-width: 800px; margin: 0 auto; background-color: white; padding: 20px; border-radius: 5px; box-shadow: 0 0 10px rgba(0,0,0,0.1); }");
        response.getWriter().println("h1 { color: #333; }");
        response.getWriter().println("h2 { color: #555; margin-top: 20px; }");
        response.getWriter().println(".section { margin-bottom: 30px; padding: 15px; border: 1px solid #ddd; border-radius: 4px; }");
        response.getWriter().println("label { display: block; margin-bottom: 5px; font-weight: bold; }");
        response.getWriter().println("input[type=text], textarea { width: 100%; padding: 8px; margin-bottom: 10px; border: 1px solid #ddd; border-radius: 4px; box-sizing: border-box; }");
        response.getWriter().println("textarea { height: 100px; }");
        response.getWriter().println("button { background-color: #4CAF50; color: white; padding: 10px 15px; border: none; border-radius: 4px; cursor: pointer; }");
        response.getWriter().println("button:hover { background-color: #45a049; }");
        response.getWriter().println(".result { margin-top: 10px; padding: 10px; background-color: #f9f9f9; border-left: 4px solid #4CAF50; }");
        response.getWriter().println("</style>");
        response.getWriter().println("</head><body>");
        response.getWriter().println("<div class='container'>");
        response.getWriter().println("<h1>实用工具</h1>");
        
        // 计时器部分
        response.getWriter().println("<div class='section'>");
        response.getWriter().println("<h2>计时器</h2>");
        response.getWriter().println("<form action='utility' method='get'>");
        response.getWriter().println("<input type='hidden' name='action' value='startTimer'>");
        response.getWriter().println("<label for='minutes'>持续时间（分钟）:</label>");
        response.getWriter().println("<input type='text' id='minutes' name='minutes' value='5'>");
        response.getWriter().println("<button type='submit'>启动计时器</button>");
        response.getWriter().println("</form>");
        response.getWriter().println("<p>启动后，计时器将每秒在日志中输出当前时间，直到指定的时间结束。</p>");
        response.getWriter().println("<form action='utility' method='get' style='margin-top: 10px;'>");
        response.getWriter().println("<input type='hidden' name='action' value='stopTimer'>");
        response.getWriter().println("<button type='submit'>停止计时器</button>");
        response.getWriter().println("</form>");
        
        // 显示计时器结果消息
        String timerMessage = request.getParameter("timerMessage");
        if (timerMessage != null && !timerMessage.isEmpty()) {
            response.getWriter().println("<div class='result'>" + timerMessage + "</div>");
        }
        response.getWriter().println("</div>");
        
        // 文件IO部分
        response.getWriter().println("<div class='section'>");
        response.getWriter().println("<h2>文件写入</h2>");
        response.getWriter().println("<form action='utility' method='post'>");
        response.getWriter().println("<input type='hidden' name='action' value='writeFile'>");
        response.getWriter().println("<label for='filename'>文件名（可选）:</label>");
        response.getWriter().println("<input type='text' id='filename' name='filename' placeholder='留空将自动生成文件名'>");
        response.getWriter().println("<label for='content'>内容:</label>");
        response.getWriter().println("<textarea id='content' name='content' placeholder='请输入要写入文件的内容'></textarea>");
        response.getWriter().println("<button type='submit'>写入文件</button>");
        response.getWriter().println("</form>");
        
        // 显示文件写入结果消息
        String fileMessage = request.getParameter("fileMessage");
        if (fileMessage != null && !fileMessage.isEmpty()) {
            response.getWriter().println("<div class='result'>" + fileMessage + "</div>");
        }
        response.getWriter().println("</div>");
        
        // 文件列表部分
        response.getWriter().println("<div class='section'>");
        response.getWriter().println("<h2>文件列表</h2>");
        response.getWriter().println("<form action='utility' method='get'>");
        response.getWriter().println("<input type='hidden' name='action' value='listFiles'>");
        response.getWriter().println("<button type='submit'>查看文件列表</button>");
        response.getWriter().println("</form>");
        response.getWriter().println("</div>");
        
        // 文件读取部分
        response.getWriter().println("<div class='section'>");
        response.getWriter().println("<h2>文件读取</h2>");
        response.getWriter().println("<form action='utility' method='get'>");
        response.getWriter().println("<input type='hidden' name='action' value='readFile'>");
        response.getWriter().println("<label for='readFilename'>文件名:</label>");
        response.getWriter().println("<input type='text' id='readFilename' name='filename' placeholder='输入要读取的文件名'>");
        response.getWriter().println("<button type='submit'>读取文件</button>");
        response.getWriter().println("</form>");
        response.getWriter().println("</div>");
        
        response.getWriter().println("</div></body></html>");
    }
    
    private void handleStartTimer(HttpServletRequest request, HttpServletResponse response) 
            throws IOException {
        
        String minutesStr = request.getParameter("minutes");
        int minutes = 5; // 默认5分钟
        
        try {
            minutes = Integer.parseInt(minutesStr);
            if (minutes > 30) {
                minutes = 30; // 限制最大30分钟
            }
        } catch (NumberFormatException e) {
            log.warn("无效的分钟数: {}, 使用默认值5", minutesStr);
        }
        
        String result = timerService.startTimer(minutes);
        log.info("计时器启动结果: {}", result);
        
        response.sendRedirect(request.getContextPath() + "/utility?timerMessage=" + 
                java.net.URLEncoder.encode(result, "UTF-8"));
    }
    
    private void handleStopTimer(HttpServletRequest request, HttpServletResponse response) 
            throws IOException {
        
        String result = timerService.stopTimer();
        log.info("计时器停止结果: {}", result);
        
        response.sendRedirect(request.getContextPath() + "/utility?timerMessage=" + 
                java.net.URLEncoder.encode(result, "UTF-8"));
    }
    
    private void handleWriteFile(HttpServletRequest request, HttpServletResponse response) 
            throws IOException {
        
        String filename = request.getParameter("filename");
        String content = request.getParameter("content");
        
        if (content == null || content.trim().isEmpty()) {
            response.sendRedirect(request.getContextPath() + "/utility?fileMessage=" + 
                    java.net.URLEncoder.encode("内容不能为空", "UTF-8"));
            return;
        }
        
        String result = fileIOService.writeToFile(content, filename);
        log.info("文件写入结果: {}", result);
        
        response.sendRedirect(request.getContextPath() + "/utility?fileMessage=" + 
                java.net.URLEncoder.encode(result, "UTF-8"));
    }
    
    private void handleListFiles(HttpServletRequest request, HttpServletResponse response) 
            throws IOException {
        
        List<String> files;
        try {
            files = fileIOService.listFiles();
            log.info("获取到{}个文件", files.size());
        } catch (Exception e) {
            log.error("列出文件时发生错误", e);
            response.sendRedirect(request.getContextPath() + "/utility?fileMessage=" + 
                    java.net.URLEncoder.encode("列出文件时发生错误: " + e.getMessage(), "UTF-8"));
            return;
        }
        
        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().println("<!DOCTYPE html>");
        response.getWriter().println("<html><head>");
        response.getWriter().println("<meta charset='UTF-8'>");
        response.getWriter().println("<title>文件列表</title>");
        response.getWriter().println("<style>");
        response.getWriter().println("body { font-family: Arial, sans-serif; margin: 0; padding: 20px; background-color: #f5f5f5; }");
        response.getWriter().println(".container { max-width: 800px; margin: 0 auto; background-color: white; padding: 20px; border-radius: 5px; box-shadow: 0 0 10px rgba(0,0,0,0.1); }");
        response.getWriter().println("h1 { color: #333; }");
        response.getWriter().println("ul { list-style-type: none; padding: 0; }");
        response.getWriter().println("li { padding: 8px; margin-bottom: 5px; background-color: #f9f9f9; border-left: 4px solid #4CAF50; }");
        response.getWriter().println("a { display: inline-block; margin-top: 20px; color: #4CAF50; text-decoration: none; }");
        response.getWriter().println("a:hover { text-decoration: underline; }");
        response.getWriter().println("</style>");
        response.getWriter().println("</head><body>");
        response.getWriter().println("<div class='container'>");
        response.getWriter().println("<h1>文件列表</h1>");
        
        if (files.isEmpty()) {
            response.getWriter().println("<p>没有找到文件</p>");
        } else {
            response.getWriter().println("<ul>");
            for (String file : files) {
                response.getWriter().println("<li>" + file + " <a href='utility?action=readFile&filename=" + 
                        java.net.URLEncoder.encode(file, "UTF-8") + "' style='font-size:smaller;'>[查看]</a></li>");
            }
            response.getWriter().println("</ul>");
        }
        
        response.getWriter().println("<a href='utility'>返回主页</a>");
        response.getWriter().println("</div></body></html>");
    }
    
    private void handleReadFile(HttpServletRequest request, HttpServletResponse response) 
            throws IOException {
        
        String filename = request.getParameter("filename");
        
        if (filename == null || filename.trim().isEmpty()) {
            response.sendRedirect(request.getContextPath() + "/utility?fileMessage=" + 
                    java.net.URLEncoder.encode("文件名不能为空", "UTF-8"));
            return;
        }
        
        String content = fileIOService.readFromFile(filename);
        log.info("读取文件 {}: 内容长度 {} 字符", filename, content.length());
        
        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().println("<!DOCTYPE html>");
        response.getWriter().println("<html><head>");
        response.getWriter().println("<meta charset='UTF-8'>");
        response.getWriter().println("<title>文件内容 - " + filename + "</title>");
        response.getWriter().println("<style>");
        response.getWriter().println("body { font-family: Arial, sans-serif; margin: 0; padding: 20px; background-color: #f5f5f5; }");
        response.getWriter().println(".container { max-width: 800px; margin: 0 auto; background-color: white; padding: 20px; border-radius: 5px; box-shadow: 0 0 10px rgba(0,0,0,0.1); }");
        response.getWriter().println("h1 { color: #333; }");
        response.getWriter().println("pre { background-color: #f9f9f9; padding: 15px; border-left: 4px solid #4CAF50; white-space: pre-wrap; word-wrap: break-word; }");
        response.getWriter().println("a { display: inline-block; margin-top: 20px; color: #4CAF50; text-decoration: none; }");
        response.getWriter().println("a:hover { text-decoration: underline; }");
        response.getWriter().println("</style>");
        response.getWriter().println("</head><body>");
        response.getWriter().println("<div class='container'>");
        response.getWriter().println("<h1>文件内容: " + filename + "</h1>");
        
        if (content.startsWith("文件不存在") || content.startsWith("读取文件时发生错误")) {
            response.getWriter().println("<p>" + content + "</p>");
        } else {
            response.getWriter().println("<pre>" + content + "</pre>");
        }
        
        response.getWriter().println("<a href='utility'>返回主页</a>");
        response.getWriter().println("<a href='utility?action=listFiles' style='margin-left: 20px;'>返回文件列表</a>");
        response.getWriter().println("</div></body></html>");
    }
} 